package com.kuroneko.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kuroneko.excel.log;

import java.util.*;
import java.util.stream.Collectors;

public class NoModelDataListener<T> extends AnalysisEventListener<Map<Integer, String>> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private static final int HEAD_COUNT = 4;
    private static final String TBL = "tbl";
    private static final String BEAN_PATH = "com.kuroneko.excel.entity.";
    private Class<?> clazz;
    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final List<Map<Integer, String>> headDataList = ListUtils.newArrayListWithExpectedSize(HEAD_COUNT);
    private final Map<Integer, String> fieldMap = MapUtils.newHashMap();
    private final Map<Integer, String> typeMap = MapUtils.newHashMap();

    public NoModelDataListener(String sheetName) {
        String beanName = BEAN_PATH + sheetName.substring(TBL.length() + 1);
        try {
            this.clazz = Class.forName(beanName);
        } catch (ClassNotFoundException e) {
            log.info(beanName + " 没找到！");
            e.printStackTrace();
        }
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        Set<Integer> keySet = fieldMap.keySet();
        Map<Integer, String> map = data.entrySet().stream().filter(e -> keySet.contains(e.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        Map<String, String> beanMap = new LinkedHashMap<>();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            beanMap.put(fieldMap.get(entry.getKey()), entry.getValue());
        }

        T o = JSON.parseObject(JSON.toJSONString(beanMap), new TypeReference<T>() {
        });

        cachedDataList.add(o);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 这里会一行行的返回头
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        headDataList.add(headMap);
        if (headDataList.size() == HEAD_COUNT) {
            Map<Integer, String> head1 = headDataList.get(1);
            Map<Integer, String> head2 = headDataList.get(2);
            Map<Integer, String> head3 = headDataList.get(3);
            head3.forEach((key, value) -> {
                if (Objects.equals(value, "r")) {
                    fieldMap.put(key, head1.get(key));
                    typeMap.put(key, head2.get(key));
                }
            });
            log.info(fieldMap.toString());
            log.info(typeMap.toString());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        cachedDataList.forEach(v -> log.info(v.toString()));
        log.info("存储数据库成功！");
    }

}

